package fa7.socialcode.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import fa7.socialcode.dao.AvaliacaoDao;
import fa7.socialcode.model.Avaliacao;

public class AvaliacaoDaoJpa implements AvaliacaoDao{
	
	  private static EntityManagerFactory factory;
	  static {
	    factory = Persistence.createEntityManagerFactory("socialcode");
	  }

	  private EntityManager entityManager;

	  private EntityManager getEntityManager() {
	    if (entityManager == null)
	      entityManager = factory.createEntityManager();
	    return entityManager;

	  }

	  public List findAvaliacoes() {
	    return getEntityManager().createQuery("from Avaliacao").getResultList();
	  }

	  public void removeAvaliacao(Avaliacao avaliacao) {
	    getEntityManager().getTransaction().begin();

	    getEntityManager().remove(avaliacao);

	    getEntityManager().getTransaction().commit();
	  }

	  public void removeAvaliacao(Long id) {
	    getEntityManager().getTransaction().begin();

	    getEntityManager().remove(findAvaliacao(id));

	    getEntityManager().getTransaction().commit();
	  }

	  public void saveAvaliacao(Avaliacao avaliacao) {
	    getEntityManager().getTransaction().begin();
	    if (avaliacao.getId() != null) {
	      getEntityManager().merge(avaliacao);
	    } else {
	      getEntityManager().persist(avaliacao);
	    }

	    getEntityManager().getTransaction().commit();
	  }

	  public Avaliacao findAvaliacao(Long id) {
	    return getEntityManager().find(Avaliacao.class, id);
	  }

	}



